import { login, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import Cookie from 'js-cookie'
import axios from 'axios'
import {getUserInfo, getUserRoles} from '@/api/global/index'
import {getLocalStorage} from '@/utils/filters'

const state = {
    token: getToken(),
    name: '',
    avatar: '',
    introduction: '',
    roles: []
}

const mutations = {
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
        state.introduction = introduction
    },
    SET_NAME: (state, name) => {
        state.name = name
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
        state.roles = roles
    },
    SET_RERENDER: (state) => {
        state.reRender++
    }
}

const actions = {
    // 用户登录（ 该方法名字在映射的时候会被改写 user/login => login ）
    login ({dispatch}, userInfo) {
        const {username, password} = userInfo
        return new Promise((resolve, reject) => {
            let params = {
                userName: username,
                password: password
            }
            login(params).then(res => {
                if (res.code.toString() === '200') {
                    Cookie.set('token', res.data, {expires: 1})
                    axios.defaults.headers['Authorization'] = 'Bearer ' + res.data
                    Promise.all([dispatch('getLoginUserInfo'), dispatch('getLoginUserRoles')]).then(response => {
                        resolve(response) // 不需要返回到登录接口，用户数据已处理
                        // resolve(res)
                    })
                } else {
                    resolve(res)
                }
            })
                .catch(err => {
                    reject(err)
                })
        })
    },
    // 重新获取用户信息
    getUserInfoAgain ({dispatch}) {
        return new Promise((resolve, reject) => {
            Promise.all([dispatch('getLoginUserInfo'), dispatch('getLoginUserRoles')]).then(res => {
                resolve(res)
            })
        })
    },

    // 获取用户信息
    getLoginUserInfo ({commit}) {
        return new Promise((resolve, reject) => {
            getUserInfo().then(res => {
                if (res.code.toString() === '200') {
                    let userInfo = {
                        realName: res.data.userName,
                        mechanism: res.data.userPowerOrgan,
                        checkAuth: res.data.userAccess
                    }
                    localStorage.setItem('userInfo', JSON.stringify(userInfo))
                    localStorage.setItem('userMechanism', JSON.stringify(res.data.userOrgan))
                    localStorage.setItem('userType', JSON.stringify(res.data.userRole.roleType))
                    let orgId = getLocalStorage('globalSearch', 'orgId')
                    // 查询详情时间限制
                    let index = res.data.userPowerOrgan.findIndex(item => item.id === orgId)
                    if (index !== -1) {
                        localStorage.setItem('viewDeadlineDays', res.data.userPowerOrgan[index].viewDeadlineDays)
                    }
                    // 科室重置或选中
                    let flagOrg = res.data.userPowerOrgan.filter(item => item.id === orgId)
                    let depId = getLocalStorage('globalSearch', 'departmentId')
                    let flagDep = JSON.stringify(res.data.userPowerOrgan).indexOf(depId) === -1
                    if (!flagOrg.length) {
                        localStorage.setItem('globalSearch', JSON.stringify({
                            ...getLocalStorage('globalSearch'),
                            orgId: '',
                            departmentId: '',
                            cykb: '',
                            cybf: '',
                            bmy: ''
                        }))
                    } else if (flagDep) {
                        localStorage.setItem('globalSearch', JSON.stringify({
                            ...getLocalStorage('globalSearch'),
                            departmentId: '',
                            cykb: '',
                            cybf: ''
                        }))
                    }
                    resolve(res)
                } else {
                    resolve(res)
                }
            }).catch(error => {
                reject(error)
            })
        })
    },

    // 获取用户拥有权限
    getLoginUserRoles ({commit}) {
        return new Promise((resolve, reject) => {
            getUserRoles().then(res => {
                if (res.code.toString() === '200') {
                    let arr = []
                    res.data.forEach(item => {
                        arr.push(parseInt(item.id))
                    })
                    arr.push(999999999999)
                    localStorage.setItem('rolesCode', JSON.stringify(arr))
                    sessionStorage.setItem('lastRequest', new Date().getTime())
                    resolve(res)
                } else {
                    resolve(res)
                }
            }).catch(error => {
                reject(error)
            })
        })
    },

    // 重新渲染组件
    updateReRender ({commit}) {
        commit('SET_RERENDER')
    },

    // get user info
    getInfo ({ commit, state }) {
        return new Promise((resolve, reject) => {
            getInfo(state.token).then(response => {
                const { data } = response

                if (!data) {
                    reject('Verification failed, please Login again.')
                }

                const { roles, name, avatar, introduction } = data

                // roles must be a non-empty array
                if (!roles || roles.length <= 0) {
                    reject('getInfo: roles must be a non-null array!')
                }

                commit('SET_ROLES', roles)
                commit('SET_NAME', name)
                commit('SET_AVATAR', avatar)
                commit('SET_INTRODUCTION', introduction)
                resolve(data)
            }).catch(error => {
                reject(error)
            })
        })
    },

    // user logout
    logout ({ commit, state, dispatch }) {
        return new Promise((resolve) => {
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            localStorage.removeItem('globalSearchDRG')
            localStorage.removeItem('globalFormDRG')
            localStorage.removeItem('globalSearchQC')
            localStorage.removeItem('globalFormQC')
            localStorage.removeItem('userInfo')
            localStorage.removeItem('userMechanism')
            localStorage.removeItem('userType')
            localStorage.removeItem('viewDeadlineDays')
            localStorage.removeItem('globalSearch')
            localStorage.removeItem('globalSearchQC')
            localStorage.removeItem('rolesCode')
            localStorage.removeItem('tagsView')
            localStorage.removeItem('tagsViewQC')
            localStorage.removeItem('tagsViewMS')
            localStorage.removeItem('searchForm')
            localStorage.removeItem('searchFormQC')
            localStorage.removeItem('searchFormMS')
            localStorage.removeItem('listQuery')
            localStorage.removeItem('cloudMode')
            Cookie.remove('sidebarStatus_drg')
            Cookie.remove('sidebarStatus')
            Cookie.remove('size')
            Cookie.remove('timeLeft')
            Cookie.remove('initlogout')
            Cookie.remove('token')
            Cookie.remove('isPackage')
            Cookie.set('optOut', 'optOut')
            sessionStorage.clear()
            resolve()
        })
    },

    // remove token
    resetToken ({ commit }) {
        return new Promise(resolve => {
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            removeToken()
            resolve()
        })
    },

    // dynamically modify permissions
    changeRoles ({ commit, dispatch }, role) {
        return new Promise(async resolve => {
            const token = role + '-token'

            commit('SET_TOKEN', token)
            setToken(token)

            const { roles } = await dispatch('getInfo')

            resetRouter()

            // generate accessible routes map based on roles
            const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

            // dynamically add accessible routes
            router.addRoutes(accessRoutes)

            // reset visited views and cached views
            dispatch('tagsView/delAllViews', null, { root: true })

            resolve()
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
